# -*- coding: utf-8 -*-


# cmap2owl -- Helper application to convert from concept maps to OWL ontologies
# Copyright (c) 2008-2013  Rodrigo Rizzi Starr
#  
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#  
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#  
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


'''
Contains a set of rules to identify enumerations

@author: Rodrigo Rizzi Starr
@copyright: Copyright © 2008-2013 Rodrigo Rizzi Starr
@license: MIT License
@contact: rodrigo.starr@gmail.com
'''


from mapperRule import MapperRule
from mapperQuestion import MapperQuestion
from infoProvider import InfoProvider, SimpleInfoProvider, UnionOfInfoProviders
from actionProvider import ActionProvider, UnionOfActionProviders
from log import log
log.debug("Loaded...")

           
            
class EnumerationRule(MapperRule):
    "Detects when the class is completely defined by the individuals"

    def __init__(self, db):
        
        # Linking phrases denoting a enumeration relation (a definition relation
        #  is the inverse of a enumeration
        classifiers = ["enumerationPhrases",
                       "definitionPhrases",
                       ]
          
        # Heuristics to identify enumerations
        rules = [
                 "inferenceGroup(enumerationRule, [enumerationClass(_,_,_)])",
                 
                 "enumerationClass(Concept, Set, Relation) :-"
                    "enumerationPhrases(Label),"
                    "label(Relation,Label),"
                    "relationBetween(Relation, Concept, _),"
                    "positive(class(Concept)),"
                    "setof(Ind, (relationBetween(Relation, Concept, Ind),"
                            "positive(individual(Ind))), Set),"
                    "\+ (isTrue(inverseRelation(R1, R2)), ("
                        "fromPartRelation(R1,Concept); "
                        "fromPartRelation(R2, Concept)))",
                 
                 "enumerationClass(Concept, Set, Relation) :-"
                    "definitionPhrases(Label),"
                    "label(Relation, Label),"
                    "relationBetween(Relation, _, Concept),"
                    "positive(class(Concept)),"
                    "setof(Ind, (relationBetween(Relation, Ind, Concept),"
                            "positive(individual(Ind))), Set),"
                    "\+ (isTrue(inverseRelation(R1, R2)), ("
                        "fromPartRelation(R1,Concept); "
                        "fromPartRelation(R2, Concept)))",
                 
                 "enumerationOWL(Class, Set) :- "
                    "isTrue(enumerationClass(Class, Set, _))",
                 "isTrue(class(Concept)) :-"
                    "isTrue(enumerationClass(Concept, _, _))",
                 "isFalse(relation(Relation)) :-"
                    "isTrue(enumerationClass(_, _, Relation))",
                 "isTrue(individual(Individual)) :-"
                    "isTrue(enumerationClass(_, Set, _)),"
                      "member(Individual, Set)",
                  ]
         
        MapperRule.__init__(self, "EnumerationRules", db, rules, classifiers)
   
    def getQuestions(self):
        "Queries the KB to find possible enumeration relations"
        
        questions = []
        query = "possible(enumerationClass(Concept, Set, Relation))"
        transitives = self.db.query(query)
        
        for answer in transitives:
            answer["Ids"] = list(answer["Set"])
            answer["Ids"].append(answer["Concept"])
            questions.append(MapperQuestion(
             self.db,
             answer,
             'Do the relation "<b>%(Relation)s</b>" means that the class '
                '<b>"%(Concept)s</b>" is defined by an enumeration of '
                '"<b>%(Set)s</b>" ?',
             "enumerationClass(%(Concept)s, %(Set)s, %(Relation)s)",
             helpFile = "enumeration"
              ))
            
        return questions
      
    def getInfoProvider(self):
        "Returns an info provider about mereologic relations"
        
        relationInfo = SimpleInfoProvider(self.db,
                            "isTrue(enumerationClass(_, _, %s))",
                            "This link defines an enumeration relation")
        
        classInfo = InfoProvider(self.db,
                            "isTrue(enumerationClass(%s, Set, _))",
                            "This class is defined as an enumeration of:")
        
        individualInfo = InfoProvider(self.db,
                            "isTrue(enumerationClass(Rel, IndSet, _)), "
                                "member(%s,IndSet), Set = [Rel]",
                            "This individual is part of "
                                "the defining enumeration of:")
        
        return UnionOfInfoProviders(relationInfo, classInfo, individualInfo)

    def getActionsProvider(self):
        """Returns actions providers for this rule"""
        
        enumeration = ActionProvider(self.db,
                            "equivalentLinkingPhrase(Element, %s),"
                                "label(Element, Label),"
                                "\+ enumerationPhrases(Label)",
                            "Does this phrase "
                                "indicate an enumeration ?",
                            "enumerationPhrases(%(Label)s)")
        
        definition = ActionProvider(self.db,
                            "equivalentLinkingPhrase(Element, %s),"
                                "label(Element, Label),"
                                "\+ definitionPhrases(Label)",
                            "Does this phrase "
                                "indicate a definition ?",
                            "definitionPhrases(%(Label)s)")
        
        return UnionOfActionProviders(enumeration, definition)
